﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace HackingSilverlightCodeBrowser
{
    public class WrapPanel : Panel
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            for (int x = 0; x < this.Children.Count; x++)
            {
                this.Children[x].Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            }
            return new Size();
        }

        protected override Size ArrangeOverride(Size FinalSize)
        {
            double Top = 0;
            double Left = 0;
            double Width = 0;
            double Height = 0;
            double NextTop = 0;

            foreach (UIElement element in this.Children)
            {
                Width = element.DesiredSize.Width;
                Height = element.DesiredSize.Height;
                if ((Left + Width) > FinalSize.Width)
                {
                    Left = 0;
                    Top = NextTop;
                    NextTop = 0;
                }
                element.Arrange(new Rect(Left, Top, Width, Height));
                Left = Left + Width;
                NextTop = Math.Max(NextTop, Top + Height);
            }
            return FinalSize;
        }  
    }
}
